const Parser = require("./parser");
const Node = require("./Node");

const stack = []; // 存储标签的栈, 父子结构的处理栈

const parser = new Parser("<div><p></p></div>");

const root = new Node();
root.start = parser.index;
root.type = "Fragment";

function tag_name_close() {
  const tagName = parser.readUntil(">");

  const current_node = stack.pop();
  current_node.end = parser.index;

  parser.next(">")

  if (current_node.name !== tagName) {
    throw new Error(`${current_node.name},标签没有匹配到,${tagName}`);
  }
}

function tag_name() {
  const node = new Node();
  node.start = parser.index - 1;
  const tagName = parser.readUntilP(/\s+|\>/);
  node.name = tagName;
  node.type = "Element";

  if (parser.next(" ")) {
    // todo: attrs
  } else if (parser.next(">")) {
    stack.push(node);
    return node;
  } else if (parser.next("/>")) {
    node.selfClosing = true;
  }
  return node;
}

function parseHTML() {
  let ch = parser.current();
  parser.skip();
  while (((ch = parser.current()), ch)) {
    let current_node = null;
    if (stack.length === 0) {
      current_node = root;
    } else {
      current_node = stack.slice(-1)[0];
    }

    if (parser.next("</")) {
      tag_name_close();
      parseHTML();
    } else if (parser.next("<")) {
      current_node.children.push(tag_name());
    }
  }
  parser.skip();
  root.end = parser.index - 1;
  return root;

}

module.exports = parseHTML;
